<script setup lang="tsx">
import Write from './components/Write.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { Table } from '@/components/Table'
import { computed, onMounted, reactive, ref, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRoute, useRouter } from 'vue-router'
import { useEventBus } from '@/hooks/event/useEventBus'
import { FormSchema } from '@/components/Form'
import { Dialog } from '@/components/Dialog'
import {
  ElButton,
  ElCheckbox,
  ElCol,
  ElCollapse,
  ElCollapseItem,
  ElForm,
  ElFormItem,
  ElInput,
  ElOption,
  ElRow,
  ElSelect,
  ElTag
} from 'element-plus'
import { TableColumn } from '@/components/Table'
import Rebut from '@/views/Check/Rebut/Rebut.vue'
import { addQARApi, getQARApi, putQARApi, putQARStampApi, putQARStatusApi } from '@/api/check/qar'
import Uploader from '@/components/AttactmentUploader/src/Uploader.vue'
import { QARType, QARWriteType } from '@/api/check/qar/types'
import { Icon } from '@iconify/vue'
import Vendor from '@/views/Check/Vendor/Vendor.vue'
import Standard from '@/views/Check/Sample/Standard/index.vue'
import { useUserStoreWithOut } from '@/store/modules/user'
import { formatToDateTime } from '@/utils/dateUtil'

const { push, go } = useRouter()
const route = useRoute()

const { t } = useI18n()

const userStore = useUserStoreWithOut()
const userStr = computed(() => userStore.getUserStr)

const schema = reactive<FormSchema[]>([
  {
    field: 'qar_no',
    label: 'QAR编号',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'form_type',
    label: '表单类型',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'material_no',
    label: '物料编码',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'product_type',
    label: '产品类型',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'part_no',
    label: '材料/零件图号',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'part_name',
    label: '材料/零件名称',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'part_type',
    label: '材料/零件类型',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'purchase_order',
    label: '采购订单号',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'flight',
    label: '架次号',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'quantity_weight',
    label: '到货数量/重量',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'vendor',
    label: '销售商',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'manufacturer',
    label: '制造商',
    colProps: {
      span: 6
    },
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <ElInput
              v-model={data.manufacturer}
              placeholder="请输入"
              v-slots={{
                append: () => (
                  <ElButton onClick={() => (vendorVisible.value = true)}>
                    <Icon icon="ep:circle-plus" />
                  </ElButton>
                )
              }}
            />
          )
        }
      }
    }
  },
  {
    field: '',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data) => {
          const tableColumns1 = reactive<TableColumn[]>([
            {
              field: 'index',
              width: 120,
              type: 'index'
            },
            {
              field: 'project',
              label: '检验项目',
              minWidth: 120
            },
            {
              field: 'is_pass',
              label: '检验结果',
              minWidth: 120,
              slots: {
                default: (scope) =>
                  scope.row.children && scope.row.children.length > 0 ? (
                    <></>
                  ) : (
                    <ElSelect v-model={scope.row!.is_pass}>
                      <ElOption label="通过" value={true}></ElOption>
                      <ElOption label="不通过" value={false}></ElOption>
                    </ElSelect>
                  )
              }
            },
            {
              field: 'attachment',
              label: '附件',
              minWidth: 120,
              slots: {
                default: (scope) =>
                  scope.row.children && scope.row.children.length > 0 ? (
                    <></>
                  ) : (
                    <Uploader v-model={scope.row!.attachment} />
                  )
              }
            },
            {
              field: 'insp_stamp',
              label: '检验印',
              minWidth: 80,
              slots: {
                default: (scope) =>
                  scope.row.children && scope.row.children.length > 0 ? (
                    <></>
                  ) : (
                    (scope.row.insp_stamp ?? (
                      <ElButton
                        onClick={() =>
                          (scope.row.insp_stamp = `${userStr.value} ${formatToDateTime(Date.now())}`)
                        }
                      >
                        检验印
                      </ElButton>
                    ))
                  )
              }
            }
          ])
          const tableColumns2 = reactive<TableColumn[]>([
            {
              field: 'index',
              label: t('common.index'),
              type: 'index',
              minWidth: 80,
              fixed: true
            },
            {
              field: 'asr_no',
              label: 'ASR编号',
              minWidth: 120
            },
            {
              field: 'status',
              label: '状态',
              minWidth: 120
            },
            {
              field: 'create_datetime',
              label: '检验记录',
              minWidth: 120
            }
          ])
          const tableColumns3 = reactive<TableColumn[]>([
            {
              field: 'index',
              label: t('common.index'),
              type: 'index',
              minWidth: 80,
              fixed: true
            },
            {
              field: 'project',
              label: '实验项',
              minWidth: 120,
              slots: {
                default: (scope) => <>{scope.row.project + ' ' + scope.row.detail_value}</>
              }
            },
            {
              field: 'order_no',
              label: '检验编号',
              minWidth: 120
            },
            {
              field: 'status',
              label: '状态',
              minWidth: 120
            },
            {
              field: 'create_datetime',
              label: '检验记录',
              minWidth: 120
            }
          ])
          const filterContentByType = (type) => {
            return data.contents?.filter((v) => v.content_type == type) || []
          }
          return (
            <ElCollapse accordion class="w-full">
              <ElCollapseItem title="零件/材料标记" name="Part_Material_Identification">
                <ElForm labelWidth="auto" labelPosition="right">
                  <ElRow gutter={20}>
                    <ElCol span={8}>
                      <ElFormItem label="图号/件号/材料牌号">
                        <ElInput v-model={data.draw_no} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="更改字母">
                        <ElInput v-model={data.rev_letter} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="状态">
                        <ElInput v-model={data.temper} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="规范/标准">
                        <ElInput
                          v-model={data.spec_stan}
                          v-slots={{
                            append: () => (
                              <ElButton onClick={() => (standVisible.value = true)}>
                                <Icon icon="ep:circle-plus" />
                              </ElButton>
                            )
                          }}
                        />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="规范/标准版次">
                        <ElInput v-model={data.spec_stan_rev} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="工艺材料编号">
                        <ElInput v-model={data.zpm_cpm} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="型别">
                        <ElInput v-model={data.typing} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="类别/组合物别">
                        <ElInput v-model={data.classing} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="级别">
                        <ElInput v-model={data.grade} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="形态/形式">
                        <ElInput v-model={data.form} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="规格">
                        <ElInput v-model={data.size} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="色号">
                        <ElInput v-model={data.color} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="性能要求">
                        <ElInput v-model={data.special_property} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="热处理/炉/批号">
                        <ElInput v-model={data.special_property} />
                      </ElFormItem>
                    </ElCol>
                  </ElRow>
                </ElForm>
              </ElCollapseItem>
              <ElCollapseItem title="实际构型信息" name="Actual_Configuration_Info">
                <ElForm labelWidth="auto" labelPosition="right">
                  <ElRow gutter={20}>
                    <ElCol span={12}>
                      <ElFormItem label="序列号">
                        <ElInput v-model={data.serial_no} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={12}>
                      <ElFormItem label="热处理/炉/批号">
                        <ElInput v-model={data.lot_batch_no} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={12}>
                      <ElFormItem label="实际零件版次">
                        <ElInput v-model={data.act_part_rev} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={12}>
                      <ElFormItem label="实际更改号或其他补充标识号">
                        <ElInput v-model={data.act_change_no} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="实际图号">
                        <ElInput v-model={data.act_draw_no} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="实际图号版次">
                        <ElInput v-model={data.act_draw_no_rev} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="实际软件件号">
                        <ElInput v-model={data.act_software_code} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="实际软件版本">
                        <ElInput v-model={data.act_software_rev} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="实际ATP编号">
                        <ElInput v-model={data.act_atp_no} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="实际ATP版本">
                        <ElInput v-model={data.act_atp_rev} />
                      </ElFormItem>
                    </ElCol>
                  </ElRow>
                </ElForm>
              </ElCollapseItem>
              <ElCollapseItem title="检验/验证特性" name="Inspected_Characteristic">
                <Table
                  data={filterContentByType('检验项目')}
                  columns={tableColumns1}
                  defaultExpandAll
                ></Table>
              </ElCollapseItem>
              <ElCollapseItem title="材料要求试验" name="Required_Test">
                <Table data={data.test_contents} columns={tableColumns3} class="w-full" />
              </ElCollapseItem>
              <ElCollapseItem title="记录" name="Record">
                <ElForm labelWidth="auto" labelPosition="right">
                  <ElRow gutter={20}>
                    <ElCol span={12}>
                      <ElFormItem label="要求尺寸">
                        <ElInput v-model={data.required_dimension} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={12}>
                      <ElFormItem label="实际测量">
                        <ElInput v-model={data.act_measurement} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={12}>
                      <ElFormItem label="试样数量">
                        <ElInput v-model={data.pclr_quantity} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={12}>
                      <ElFormItem label="试样规格/尺寸">
                        <ElInput v-model={data.pclr_size} />
                      </ElFormItem>
                    </ElCol>
                  </ElRow>
                </ElForm>
              </ElCollapseItem>
              <ElCollapseItem title="限制要求" name="Limit_Requirement">
                <ElForm labelWidth="auto" labelPosition="right" class="ml-10">
                  {filterContentByType('限制要求').map((item) => {
                    return (
                      <div class="flex mb-10px">
                        <ElCheckbox label={item.project} v-model={item.check} />
                        {item.detail.map((detail, i) => {
                          return (
                            <div class="flex items-center	ml-10px">
                              <ElInput v-model={item.detail_value[i]} placeholder={detail} />
                            </div>
                          )
                        })}
                      </div>
                    )
                  })}
                </ElForm>
              </ElCollapseItem>
              <ElCollapseItem title="ASR检验信息" name="ASR_Inspect">
                <Table data={data.asr_forms} columns={tableColumns2} class="w-full" />
              </ElCollapseItem>
              <ElCollapseItem title="限寿要求" name="Life_Limit">
                <ElForm labelWidth="auto" labelPosition="right" class="ml-10">
                  <ElRow gutter={20}>
                    <ElCol span={2}>
                      <ElCheckbox v-model={data.is_life_limit} label="是否限寿件" />
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="工程要求">
                        <ElInput v-model={data.life_limit_req} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="基准日期">
                        <div class="flex flex-nowrap w-full">
                          <ElInput v-model={data.life_limit_manage} placeholder="管控方式" />
                          <ElInput v-model={data.life_limit_date} class="ml-10px" />
                        </div>
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="库房存储期限">
                        <ElInput v-model={data.life_limit_period} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="基实物信息">
                        <ElInput v-model={data.product_information} />
                      </ElFormItem>
                    </ElCol>
                  </ElRow>
                </ElForm>
              </ElCollapseItem>
              <ElCollapseItem title="其他内容" name="Other">
                <ElForm labelWidth="auto" labelPosition="right" class="ml-10">
                  <ElRow gutter={20}>
                    <ElCol span={6}>
                      <ElFormItem label="计划备注">
                        <ElInput v-model={data.plan_remark} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="检验备注">
                        <ElInput v-model={data.insp_remark} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="实际重量">
                        <ElInput v-model={data.actual_weight} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="重量来源">
                        <ElInput v-model={data.source_of_weight} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="FRR编号">
                        <ElInput v-model={data.frr_no} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="合格数">
                        <ElInput v-model={data.acceptable_quant} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="拒收数">
                        <ElInput v-model={data.rejective_quant} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="合格率">
                        <ElInput v-model={data.conformity_rate} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="质量计划">
                        {data.prepared_by ? (
                          data.prepared_by
                        ) : (
                          <ElButton onClick={() => updateStamp(data, 'prepared_by')}>刷卡</ElButton>
                        )}
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="质量检验">
                        {/* <ElInput v-model={data.inspected_by} /> */}
                        {data.inspected_by ? (
                          data.inspected_by
                        ) : (
                          <ElButton onClick={() => updateStamp(data, 'inspected_by')}>
                            刷卡
                          </ElButton>
                        )}
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="准予归档">
                        <ElInput v-model={data.ok_to_file} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="更改情况">
                        <ElInput v-model={data.changes} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="附件">
                        <Uploader v-model={data.attachment} />
                      </ElFormItem>
                    </ElCol>
                  </ElRow>
                </ElForm>
              </ElCollapseItem>
            </ElCollapse>
          )
        }
      }
    }
  }
])

const currentRow = ref<QARWriteType>({
  asr_features: [] as any[],
  contents: [] as any[]
})

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const formData = await unref(writeRef)?.submit()
  if (formData) {
    try {
      loading.value = true
      if (currentRow.value?.id) {
        const res = await putQARApi({ ...formData, id: currentRow.value.id })
        if (res) refresh()
      } else {
        const res = await addQARApi('single', { ...formData })
        if (res) refresh(res.data)
      }
    } finally {
      loading.value = false
    }
  }
}

// 更新状态
const updateStatus = async (status: string | undefined = undefined) => {
  const res = await putQARStatusApi({ id: currentRow.value?.id, status })
  if (res) refresh()
}

// 刷卡
const updateStamp = async (row, type) => {
  const res = await putQARStampApi(row.id, { type })
  if (res) refresh()
}

// 驳回历史
const rebutVisible = ref(false)
const rebutActionType = ref()
const rebutParams = ref()
const rebutAction = (action: string) => {
  rebutVisible.value = true
  rebutActionType.value = action
  rebutParams.value =
    action === 'add'
      ? {
          rebut_type: 'QAR',
          rebut_form_no: currentRow.value?.qar_no,
          before_status: currentRow.value?.status
        }
      : {
          rebut_type: 'QAR',
          rebut_form_no: currentRow.value?.qar_no
        }
}

const refresh = async (data: any | undefined = undefined) => {
  const id = data?.id || currentRow.value?.id
  if (id) {
    const res = await getQARApi({ id })
    if (res) currentRow.value = { ...res.data }
  }
}

// 选择供应商
const vendorRef = ref<ComponentRef<typeof Vendor>>()
const vendorVisible = ref(false)

const onSelectVendor = async () => {
  const write = unref(vendorRef)
  const formData = await write?.submit()
  if (formData) {
    currentRow.value = {
      ...currentRow.value,
      manufacturer: formData.map((item) => item.vendor).join(';')
    }
  }
  vendorVisible.value = false
}

// 选择标准
const standRef = ref<ComponentRef<typeof Standard>>()
const standVisible = ref(false)

const onSelectStand = async () => {
  const write = unref(standRef)
  const formData = await write?.submit()
  if (formData) {
    currentRow.value = {
      ...currentRow.value,
      spec_stan: formData[0].group_name,
      spec_stan_rev: 'V1'
    }
  }
  standVisible.value = false
}

// 初始化，获取详情
onMounted(async () => {
  const params = {
    ...route.params,
    ...route.query
  }
  refresh(params)
})

// 监听驳回
useEventBus({
  name: 'addRebut',
  callback: () => {
    refresh()
  }
})
</script>

<template>
  <ContentDetailWrap>
    <Write ref="writeRef" :form-schema="schema" :current-row="currentRow" />
    <template #header>
      <div class="flex justify-between items-center">
        <div>
          <ElButton @click="go(-1)">
            {{ t('common.back') }}
          </ElButton>
          <ElButton @click="save" v-if="!currentRow?.status">发布</ElButton>
          <ElButton @click="save" v-if="currentRow?.status == '检验中'">保存修改</ElButton>
          <ElButton v-if="currentRow?.status == '已发布'" @click="updateStatus()">
            开始检验
          </ElButton>
          <ElButton v-if="currentRow?.status == '检验中'" @click="updateStatus()">
            提交委托
          </ElButton>
          <ElButton v-if="currentRow?.status == '委托中'" @click="updateStatus()">
            检验完成
          </ElButton>
          <ElButton v-if="currentRow?.status == '检验完成'" @click="updateStatus()">
            提交归档
          </ElButton>
          <ElButton
            @click="rebutAction('add')"
            v-if="['检验中', '委托中', '检验完成'].includes(currentRow?.status ?? '')"
          >
            驳回
          </ElButton>
          <ElButton
            v-if="['已发布', '检验中', '委托中', '检验完成'].includes(currentRow?.status ?? '')"
            @click="updateStatus('作废')"
          >
            作废
          </ElButton>
          <!-- <ElButton>拆分QAR</ElButton> -->
          <!-- <ElButton>打印</ElButton> -->
        </div>
        <div class="mr-10">
          <ElTag type="success">{{ currentRow?.status ?? '未创建' }}</ElTag>
        </div>
      </div>
    </template>

    <Dialog v-model="vendorVisible" title="选择供应商">
      <Vendor ref="vendorRef" />
      <template #footer>
        <ElButton type="primary" @click="onSelectVendor">确定</ElButton>
        <ElButton @click="vendorVisible = false">{{ t('common.close') }}</ElButton>
      </template>
    </Dialog>

    <Dialog v-model="standVisible" title="选择标准">
      <Standard ref="standRef" />
      <template #footer>
        <ElButton type="primary" @click="onSelectStand">确定</ElButton>
        <ElButton @click="standVisible = false">{{ t('common.close') }}</ElButton>
      </template>
    </Dialog>
  </ContentDetailWrap>

  <Rebut v-model="rebutVisible" :action="rebutActionType" :params="rebutParams" />
</template>

<style lang="less" scoped>
:deep(.el-collapse-item__header) {
  display: unset;
  font-size: 16px;
  font-weight: 600;
  background-color: #f2f2f2;
  margin-bottom: 20px;
}
:deep(.el-form-item) {
  margin-bottom: 18px;
}
:deep(.content_wrap .el-form-item) {
  margin-bottom: 0;
}
</style>
@/hooks/event/useEventBus
